const prompt = require("prompt");
const path = require("path");
const fs = require("fs");
const _ = require("loadsh");
const execa = require("execa");
const ora = require("ora");
const envPath = path.join("./", ".env");
let config = {};

prompt.start();

async function parseConfig() {
  const file = await fs.promises.readFile(envPath);

  const lines = file.toString().split("\r\n");
  let versionIndex = 0;
  let targetVersion = "";

  for (const i in lines) {
    const line = lines[i];
    const index = line.indexOf("=");

    const name = _.trim(line.substr(0, index));
    let value = _.trim(line.substr(index + 1));

    if (name === "VERSION") {
      console.log(value)

      // m:主版本号 s：次版本号 e：最末版本号，最大不能超过100
      let [m, s, e] = value
        .replace(/\'/g, "")
        .split(".")
        .map((v) => parseInt(v, 10));

      if (e < 100) {
        e++;
      } else {
        e = 0;
        if (s < 100) {
          s++;
        } else {
          s = 0;
          m++;
        }
      }

      config[name] = `${[m, s, e].join(".")}`;
    } else {
      config[name] = value;
    }
  }

  return { lines, versionIndex, targetVersion };
}

async function sleep(time) {
  return new Promise((resolve) => {
    const timer = setTimeout(() => {
      clearTimeout(timer);

      resolve();
    }, time);
  });
}

async function writeConfig() {
  const source = await (await fs.promises.readFile(path.join("./", "config.default"))).toString();

  const data = source
    .replace("#api", config.API_URL)
    .replace("#encrypt", config.ENCRYPT);

  await fs.promises.writeFile(path.join("./", "dist", "config.js"), data);
}

async function resolve() {
  await parseConfig();

  const properties = {
    properties: {
      version: {
        description: "请输入发布版本号",
        default: config.VERSION,
        pattern: /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/,
      },
    },
  };

  const res = await prompt.get(properties);

  config.VERSION = res.version;
  const version = `v${res.version}`;

  const spanner = ora("buid").start();
  spanner.text = "write env file";
  spanner.start();

  const envData = Object.entries(config)
    .map(([key, value]) => `${key} = ${value}`)
    .join("\r\n");
  await fs.promises.writeFile(envPath, envData);

  
  spanner.text = "yarn build";
  await execa("yarn build");
  await writeConfig();

  await sleep(1000);
  spanner.stop();

  spanner.text = "commiting";
  spanner.start();
  await execa("git add", ["."]);
  await execa("git commit", ["-m", `release: ${version}`]);
  await sleep(1000);
  spanner.stop();
  spanner.text = "commiting tag";
  spanner.start();
  await execa(`git tag`, ["-a", version, "-m", `release: ${version}`]);

  await execa("git push");
  await execa("git push", ["origin", version]);

  await sleep(1000);
  spanner.stopAndPersist({ text: "done" });
}

resolve();
